//
//  BMAlertView.m
//  bigmama
//
//  Created by huyuchen on 2017/8/23.
//  Copyright © 2017年 盛成文化. All rights reserved.
//

#import "BMAlertView.h"
#import "UIImage+BMAlertBlurEffects.h"

#define kAlertWidth SCREEN_WIDTH - ResizeW(80)
#define kAlertPaddingV 11
#define kAlertPaddingH 18
#define kAlertButtonHeight 45
#define kAlertRadius 12

@interface BMAlertView ()<UIGestureRecognizerDelegate>
{
    CGFloat _scrollBottom;
    CGFloat _buttonsHeight;
    CGFloat _maxContentWidth;
    CGFloat _maxAlertViewHeight;
}
//自定义UIView
@property (nonatomic, strong) UIView *subView;
//遮罩单击手势
@property (nonatomic, strong) UITapGestureRecognizer *dismissTap;
//标题
@property (nonatomic, copy) NSString *title;
//内容
@property (nonatomic, copy) NSString *message;
//按钮名称
@property (nonatomic, strong) NSArray *buttonTitles;
//按钮颜色
@property (nonatomic, strong) NSArray *buttonTitlesColor;
//容器(存放标题和内容)
@property (nonatomic, strong) UIImageView *containerView;
//容器适配(防止小屏幕因为内容过多而不显示)
@property (nonatomic, strong) UIScrollView *scrollView;

//标题控件
@property (nonatomic, strong) UILabel *titleLabel;
//内容控件
@property (nonatomic, strong) UILabel *messageLabel;
//按钮数组
@property (nonatomic, strong) NSMutableArray *buttons;
//分割线数组
@property (nonatomic, strong) NSMutableArray *lines;
//模糊背景
//@property (nonatomic, strong) UIImageView *blurImageView;


//@property (nonatomic, strong) UIImageView *imageView;
//@property (nonatomic, strong) UIImage *image;

//宽
@property (nonatomic, assign) CGFloat viewWidth;
//高
@property (nonatomic, assign) CGFloat viewHeight;
//是否正在执行动画
@property (nonatomic, assign) BOOL isAnimating;
@property (nonatomic, assign) BOOL isCenter;
@end

@implementation BMAlertView
#pragma mark - 初始化方法
+ (instancetype)showCustomView:(UIView *)customView isCenter:(BOOL)isCenter configuration:(void(^)(BMAlertView *tempView))configuration{
    BMAlertView *tempView = [[BMAlertView alloc] initWithCustomView:customView isCenter:isCenter];
    __weak typeof(BMAlertView) *weakTempView = tempView;
    if (configuration) {
        configuration(weakTempView);
    }
    [tempView showAlert];
    return tempView;
}

+ (void)showAlertWithTitle:(NSString *)title
                   message:(NSString *)message
              buttonTitles:(NSArray<NSString *> *)buttonTitles
         buttonTitlesColor:(NSArray<UIColor *> *)buttonTitlesColor
             configuration:(void(^)(BMAlertView *view))configuration
                clickBlock:(ButtonClickBlock)clickBlock{
    
    BMAlertView *tempView = [[BMAlertView alloc] showTitle:title message:message buttonTitles:buttonTitles buttonTitlesColor:buttonTitlesColor];
    
    if (configuration) {
        configuration(tempView);
    }
    
    [tempView showAlert];
    
    tempView.buttonClickBlock = clickBlock;
    
}

- (instancetype)initWithCustomView:(UIView *)customView isCenter:(BOOL)isCenter {
    if (self = [super initWithFrame:CGRectZero]) {
        self.subView = customView;
        _isCenter = isCenter;
        [self setupUI];
    }
    return self;
}

- (instancetype)showTitle:(NSString *)title message:(NSString *)message buttonTitles:(NSArray<NSString *> *)buttonTitles buttonTitlesColor:(NSArray<UIColor *> *)buttonTitlesColor{
    
    self.viewWidth    = SCREEN_WIDTH;
    self.viewHeight   = SCREEN_HEIGHT;
    
    if (self == [super initWithFrame:CGRectZero])
    {
        _title = [title copy];
        _message = [message copy];
        _buttonTitles = [NSArray arrayWithArray:buttonTitles];
        _buttonTitlesColor = [NSArray arrayWithArray:buttonTitlesColor];
        
        [self loadUI];
    }
    return self;
}

#pragma mark - UI
- (void)setupUI{
    self.viewWidth = SCREEN_WIDTH;
    self.viewHeight = SCREEN_HEIGHT;
    
    self.frame = [UIScreen mainScreen].bounds;

    self.backgroundColor = Color_RGBA(0, 0, 0, 0.5);
    
    self.subView.layer.shadowColor   = [UIColor colorWithWhite:0 alpha:0.5].CGColor;
    self.subView.layer.shadowOffset  = CGSizeZero;
    self.subView.layer.shadowOpacity = 1;
    self.subView.layer.shadowRadius  = kAlertRadius;

    [self addSubview:self.subView];
    
    CGFloat subViewX = self.subView.frame.origin.x;
    if (self.subView.frame.size.width > 0 && subViewX  < 1) {
        subViewX = (SCREEN_WIDTH - self.subView.frame.size.width) / 2;
        subViewX = MAX(subViewX, 0);
    }
    CGFloat subViewY = self.subView.frame.origin.y;
    
    [self.subView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ResizeW(subViewX));
        make.right.mas_equalTo(-ResizeW(subViewX));
        if (_isCenter) {
            make.center.equalTo(self);
            if (self.subView.size.height > 0){
                make.height.mas_equalTo(self.subView.size.height);
            }
            else if (self.subView.origin.y > 0) {
                make.top.mas_equalTo(subViewY);
            }
            else{
                make.height.mas_equalTo(250);
            }
        }
        else {
            if (self.subView.size.height > 0){
                make.height.mas_equalTo(self.subView.size.height);
            }
            if (subViewY > 0) {
                make.top.mas_equalTo(subViewY);
            }
            else {
                make.center.equalTo(self);
            }
        }

    }];
    
    [self setupCommonUI];
}

- (void)loadUI{
    _buttons = @[].mutableCopy;
    _lines = @[].mutableCopy;
    
    _containerView = [UIImageView new];
    _containerView.userInteractionEnabled = YES;
    _containerView.layer.cornerRadius = kAlertRadius;
    _containerView.layer.masksToBounds = YES;
    _containerView.backgroundColor = [UIColor whiteColor];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [_containerView addSubview:_scrollView];
    
    [self addSubview:_containerView];
    
    [self setupCommonUI];
}

- (void)setupCommonUI{
    if (self.isShowOverlay) {
//        self.blurEffectStyle = DSAlertBlurEffectStyleLight;
    }
    [self addGestureRecognizer:self.dismissTap];
}

- (void)prepareForShow{
    [self resetViews];
    
    _scrollBottom = 0;
    _maxContentWidth = kAlertWidth-2*kAlertPaddingH;
    _maxAlertViewHeight = self.viewHeight - 50;
    CGFloat insetY = kAlertPaddingV;
    _buttonsHeight = kAlertButtonHeight*((_buttonTitles.count>2||_buttonTitles.count==0)?_buttonTitles.count:1);
    
    [self setupTitle];
    
    [self setupContent];
    
    self.frame = self.window.bounds;
    
//    self.backgroundColor = self.bgColor;
    self.backgroundColor = RGBA(0, 0, 0, 0.5f);
    
    _containerView.frame = CGRectMake(0, 0, kAlertWidth, MIN(MAX(_scrollBottom+2*insetY+_buttonsHeight, 2*kAlertRadius+kAlertPaddingV), _maxAlertViewHeight));
    _scrollView.frame = CGRectMake(0, insetY, CGRectGetWidth(_containerView.frame),MIN(_scrollBottom, CGRectGetHeight(_containerView.frame)-2*insetY-_buttonsHeight));
    _scrollView.contentSize = CGSizeMake(_maxContentWidth, _scrollBottom);
    
    [self setupButtons];
}

#pragma mark - 显示隐藏
//缩放进场动画
- (void)showAnimationWithView:(UIView *)animationView finish:(void(^)())finish{
    self.isAnimating = YES;
    BMWeakSelf
    animationView.transform = CGAffineTransformMakeScale(0.001f, 0.001f);
    [UIView animateWithDuration:0.35f animations:^{
        animationView.transform = CGAffineTransformMakeScale(1.18f, 1.18f);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25f animations:^{
            animationView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
        } completion:^(BOOL finished) {
            weakSelf.isAnimating = NO;
            if (finish) {
                finish();
            }
        }];
    }];
}

//缩放出场动画
- (void)dismissAnimationWithView:(UIView *)animationView finish:(void(^)())finish{
    self.isAnimating = YES;
    BMWeakSelf
    [UIView animateWithDuration:0.15f animations:^{
        animationView.transform = CGAffineTransformMakeScale(1.18f, 1.18f);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25f animations:^{
            animationView.transform = CGAffineTransformMakeScale(0.0001f, 0.0001f);
        } completion:^(BOOL finished) {
            weakSelf.isAnimating = NO;
            [weakSelf performSelector:@selector(removeSelf)];
            if (finish) {
                finish();
            }
        }];
    }];
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    if (!self.isAnimating)
    {
        [self layoutMySubViews];
    }else {
        
    }
}

- (void)layoutMySubViews{
    self.viewHeight = [UIScreen mainScreen].bounds.size.height;
    self.viewWidth = [UIScreen mainScreen].bounds.size.width;
    
    if (self.subView) {

    }
    else {
        [self prepareForShow];
        self.containerView.center = CGPointMake(self.viewWidth/2.f, self.viewHeight/2.f);
    }
}

- (void)showAlert{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];

    [keywindow addSubview:self];
    
    [self layoutMySubViews];
    
    if (self.subView) {
        [self showAnimationWithView:self.subView finish:nil];
    }
    else {
        [self showAnimationWithView:self.containerView finish:nil];
    }
}

- (void)dismissTapClick{
    if (self.isTouchEdgeHide) {
        NSLog(@"开启点击遮罩隐藏...开始隐藏");
        [self dismissAlert];
    }
    else {
        NSLog(@"关闭点击遮罩隐藏...若要开启,请设置isTouchEdgeHide为YES");
    }
}

- (void)dismissAlert{
    if (self.subView)
    {
        [self dismissAnimationWithView:self.subView finish:nil];
    }
    else if (self.containerView)
    {
        [self dismissAnimationWithView:self.containerView finish:nil];
    }
}

- (void)buttonClicked:(UIButton *)btn{
    [self dismissAlert];
    if (self.buttonClickBlock){
        self.buttonClickBlock(btn.tag);
    }
}

#pragma mark - 初始化标题
- (void)setupTitle{
    if (!_title){
        return;
    }
    if (!_titleLabel)
    {
        _titleLabel = [UILabel new];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.font = [UIFont systemFontOfSize:17.f];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.numberOfLines = 0;
    }
    _titleLabel.text              = _title;
    [self addLabel:_titleLabel maxHeight:100];
    [self addLine:CGRectMake(kAlertPaddingH, _scrollBottom, _maxContentWidth, 0.5) toView:_scrollView];
    _scrollBottom += kAlertPaddingV;
}

#pragma mark - 初始化内容
- (void)setupContent{
    if (!_message){
        
        if (self.lines && self.lines.count>0) {
            UIView *line = [self.lines lastObject];
            [line removeFromSuperview];
            [self.lines removeObject:line];
        }
        
        if (self.titleLabel) {
            CGRect frame = self.titleLabel.frame;
            frame.origin.y += kAlertPaddingV * 0.5;
            self.titleLabel.frame = frame;
        }
        
        return;
    }
    
    if (!_messageLabel){
        _messageLabel = [UILabel new];
        _messageLabel.textColor = [UIColor blackColor];
        _messageLabel.font = [UIFont systemFontOfSize:14];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.numberOfLines = 0;
    }
    _messageLabel.text = _message;
    [self addLabel:_messageLabel maxHeight:100000];
}

#pragma mark - 初始化按钮
- (void)setupButtons{
    if (!_buttonTitles || _buttonTitles.count == 0){
        return;
    }
    
    if (!_buttonTitlesColor || _buttonTitlesColor.count == 0 || _buttonTitlesColor.count <_buttonTitles.count){
        NSMutableArray *mutArr = [NSMutableArray array];
        for (NSInteger i = 0; i < _buttonTitles.count; i ++)
        {
            [mutArr addObject:ColorDefalutBrown];
        }
        _buttonTitlesColor = [mutArr mutableCopy];
    }
    CGFloat buttonHeight = kAlertButtonHeight;
    CGFloat buttonWidth = kAlertWidth;
    CGFloat top = CGRectGetHeight(_containerView.frame)-_buttonsHeight;
    [self addLine:CGRectMake(0, top-0.5, buttonWidth, 0.5) toView:_containerView];
    
    if (_buttonTitlesColor.count)
    {
        for (NSUInteger j = 0; j < _buttonTitlesColor.count; j++)
        {
            
            if (1 == _buttonTitles.count)
            {
                [self addButton:CGRectMake(0, top, buttonWidth, buttonHeight) title:[_buttonTitles firstObject] tag:0  titleColor:_buttonTitlesColor[0]];
            }
            else if (2 == _buttonTitles.count)
            {
                [self addButton:CGRectMake(0, top, buttonWidth/2, buttonHeight) title:[_buttonTitles firstObject] tag:0 titleColor:_buttonTitlesColor[0]];
                [self addButton:CGRectMake(0+buttonWidth/2, top, buttonWidth/2, buttonHeight) title:[_buttonTitles lastObject] tag:1 titleColor:_buttonTitlesColor[1]];
                [self addLine:CGRectMake(0+buttonWidth/2-.5, top, 0.5, buttonHeight) toView:_containerView];
            }
            else
            {
                for (NSInteger i=0; i<_buttonTitles.count; i++)
                {
                    [self addButton:CGRectMake(0, top, buttonWidth, buttonHeight) title:_buttonTitles[i] tag:i titleColor:_buttonTitlesColor[i]];
                    top += buttonHeight;
                    if (_buttonTitles.count-1!=i)
                    {
                        [self addLine:CGRectMake(0, top, buttonWidth, 0.5) toView:_containerView];
                    }
                }
                [_lines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                    [_containerView bringSubviewToFront:obj];
                }];
            }
            
        }
    }
    
}

#pragma mark - 销毁
- (void)resetViews{
    if (_titleLabel) {
        [_titleLabel removeFromSuperview];
        _titleLabel.text = @"";
    }
    
    if (_messageLabel) {
        [_messageLabel removeFromSuperview];
        _messageLabel.text = @"";
    }
    
    if (_buttons.count > 0) {
        [_buttons makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_buttons removeAllObjects];
    }
    
    if (_lines.count > 0) {
        [_lines makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_lines removeAllObjects];
    }
}

- (void)removeSelf{
    [self resetViews];
    
    [self.buttons removeAllObjects];
    [self.lines removeAllObjects];
    
//    self.blurEffectStyle = 0;
    
    [self.containerView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    [self removeFromSuperview];
}

- (void)dealloc{
    NSLog(@"[%@]销毁了",NSStringFromClass([self class]));
}

#pragma mark - setter
//- (void)setBlurEffectStyle:(BMAlertViewBlurEffectStyle)blurEffectStyle{
//    _blurEffectStyle = blurEffectStyle;
//    
//    if (!self.isShowOverlay) {
//        return;
//    }
//    
//    if (self.blurEffectStyle == DSAlertBlurEffectStyleLight)
//    {
//        self.blurImageView.image = [self.blurImageView.image alert_ApplyLightEffect];
//    }
//    else if (self.blurEffectStyle == DSAlertBlurEffectStyleExtraLight)
//    {
//        self.blurImageView.image = [self.blurImageView.image alert_ApplyExtraLightEffect];
//    }
//    else if (self.blurEffectStyle == DSAlertBlurEffectStyleDark)
//    {
//        self.blurImageView.image = [self.blurImageView.image alert_ApplyDarkEffect];
//    }
//}

- (void)setIsShowOverlay:(BOOL)isShowOverlay{
    _isShowOverlay = isShowOverlay;
    if (isShowOverlay) {
//        if (!self.blurEffectStyle) {
//            self.blurEffectStyle = DSAlertBlurEffectStyleLight;
//        }
//        else {
//            self.blurEffectStyle = self.blurEffectStyle;
//        }
        self.backgroundColor = RGBA(0, 0, 0, 0.5f);
    }
    else{
        self.backgroundColor = [UIColor clearColor];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.subView]) {
        return NO;
    }
    return YES;
}

#pragma mark - lazy getter

- (UITapGestureRecognizer *)dismissTap{
    if (!_dismissTap) {
        _dismissTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissTapClick)];
        _dismissTap.delegate = self;
    }
    return _dismissTap;
}

//- (UIImageView *)blurImageView
//{
//    if ( !_blurImageView )
//    {
//        _blurImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//        _blurImageView.image = [self screenShotImage];
//        _blurImageView.contentMode = UIViewContentModeScaleAspectFill;
//        _blurImageView.clipsToBounds = true;
//        _blurImageView.backgroundColor = [UIColor clearColor];
//        [self addSubview:_blurImageView];
//        [self sendSubviewToBack:_blurImageView];
//    }
//    return _blurImageView;
//}

#pragma mark - helper
- (UIImage *)screenShotImage
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH), YES, 1.f);
    //    /*! 设置截屏大小 */
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    [[window layer] renderInContext:UIGraphicsGetCurrentContext() ];
    
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return viewImage;
}

- (void)addLabel:(UILabel *)label maxHeight:(CGFloat)maxHeight
{
    CGSize size   = [label sizeThatFits:CGSizeMake(_maxContentWidth, maxHeight)];
    label.frame   = CGRectMake(kAlertPaddingH, _scrollBottom+kAlertPaddingV*0.5, _maxContentWidth, size.height);
    [_scrollView addSubview:label];
    _scrollBottom = CGRectGetMaxY(label.frame)+kAlertPaddingV*0.5;
}

- (void)addLine:(CGRect)frame toView:(UIView *)view
{
    UIView *line = [[UIView alloc] initWithFrame:frame];
    line.backgroundColor = ColorSepLine;
    [view addSubview:line];
    [_lines addObject:line];
}

- (void)addButton:(CGRect)frame title:(NSString *)title tag:(NSInteger)tag titleColor:(UIColor *)titleColor
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.tag = tag;
    
    if (titleColor)
    {
        [button setTitleColor:titleColor forState:UIControlStateNormal];
    }
    else
    {
        [button setTitleColor:ColorDefalutBrown forState:UIControlStateNormal];
    }
    
    if (self.bgImageName)
    {
//        [button setBackgroundImage:[self imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
//        [button setBackgroundImage:[self imageWithColor:DS_COLOR(135, 140, 145, 0.45)] forState:UIControlStateHighlighted];
    }
    else
    {
//        [button setBackgroundImage:[self imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
//        [button setBackgroundImage:[self imageWithColor:DS_COLOR(135, 140, 145, 0.45)] forState:UIControlStateHighlighted];
    }
    
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_containerView addSubview:button];
    [_buttons addObject:button];
}
@end
